package com.redshark.wmm.MeasurementProcessing;

import android.util.Log;

import com.redshark.wmm.MeasurementRequestor;

public class FrequencyProcessor implements MeasurementProcessor {
	
	private static final String TAG = "FrequencyProcessor";
	
	private static final int CFG_FREQ_LOW = 0x00;
	private static final int CFG_FREQ_HIGH = 0x01;
	
	private static final int ACK_COUNTER_OVERFLOW = 0x06;
	private static final int ACK_COUNTER_EDGE_NOT_FOUND = 0x07;
	
	public static double processMeasurement(int ADReading, int channel) {
		// TODO Auto-generated method stub
		return 0;
	}

	public Measurement displayMeasurement(int[] data, int ack,
			boolean ackPresent, MeasurementRequestor requestor) {
		double freq = 0;
		Measurement measurement;
		if (!ackPresent) {

			if (requestor.getCfg() == CFG_FREQ_HIGH) {
				freq = (64E6 / data[0]);
			} else {
				freq = (2E6 / data[0]);
			}

			if (freq > 1000) { // See Excel Spreadsheet for why this is 1000
				requestor.setCfg(CFG_FREQ_HIGH);
			}

		} else {
			if (ack == ACK_COUNTER_OVERFLOW) {
				requestor.setCfg(CFG_FREQ_LOW);
			} else if (ack == ACK_COUNTER_EDGE_NOT_FOUND) {
				Log.d(TAG, "Counter edge not found");
			}
		}
		
		//Do some formatting
		double oldFreq = freq;
		if(freq>1000000){
			freq /= 1000000;
			measurement = new Measurement(freq, 3, "MHz", oldFreq);
		}
		else if(freq>1000){
			freq /= 1000;
			measurement = new Measurement(freq, 3, "KHz", oldFreq);
		}
		else{
			measurement = new Measurement(freq, 3, "Hz", oldFreq);
		}
		return measurement;

	}

	@Override
	public Measurement displayMeasurement(int[] data) {
		// TODO Auto-generated method stub
		return null;
	}

}
